﻿
$(function () {
    lzLoading();
    // tab home
    tabClick();
    // sort
    loadSortClick();
    // cate click
    CategoryClick();
    // back top
    backToTop();

    // send Email click
    $('.regBorder input[type=button]').click(function () {
        var cmd = $(this);
        var email = cmd.parent().children('input[name$=txtEmail]').val();
        if (email == undefined || email == '' || !isValidEmailAddress(email)) {
            cmd.parent().parent().find('.errEmail').stop(true, true).fadeOut().fadeIn().delay(5000).fadeOut();
            return false;
        }
        // add email
        $.ajax({
            type: 'POST',
            dataType: 'html',
            data: { email: email },
            cache: false,
            url: '/PromotionPage/AddEmail',
            success: function (data) {
                if (data == '1') {
                    alert('Cảm ơn bạn đã quan tâm \nBabo sẽ gửi thông báo cho bạn mỗi khi có chương trình khuyến mại');
                } else {
                    cmd.parent().parent().find('.errEmail').text('Email này đã được đăng ký');
                    cmd.parent().parent().find('.errEmail').stop(true, true).fadeOut().fadeIn().delay(5000).fadeOut();
                }

                // load sort
                loadSortClick();
            },
            error: function () {
                Console.log('Đã có lỗi xảy ra!');
            }
        });

    });
});

function ReturnPagingAjax() {
    var page = $('input[name$=hidCurrentPage').val();
    var totalRecord = $('#totalRecord').text();
    var itemRecord = $('input[name$=hidItemRecord_' + page).val();

    return parseInt(totalRecord) - parseInt(itemRecord)
    //$('#endRecord').text(parseInt(totalRecord) - parseInt(itemRecord));
}

function lzLoading() {
    // load src cua cac img cho lazy load thuan tien cho seo
    $("img.lzLoading").each(function () {
        $(this).attr("data-original", $(this).attr("src"));
        $(this).attr("src", "/images/icons/blank.gif");
    });
    //lazy load
    $('img.lzLoading').lazyload({
        effect: "fadeIn"
        //threshold: 200
    });
}

function tabClick() {
    // select Tab home
    $('.menuTab li a').click(function () {
        var cmd = $(this);
        $('.menuTab li a').removeClass('tabac');
        $('.menuTab li a').addClass('menuOpa');
        cmd.addClass('tabac');
        cmd.removeClass('menuOpa');
        var idata = cmd.attr('idata');
        var cdata = cmd.attr('cdata');
        var cmdPlc = $('#plcListPromotion');
        $('.plcLoding').append('<img src="/images/icons/gif-load-small.gif" width="30" height="30" class="promo-loading" />')
        // load product
        setTimeout(function () {
            $.ajax({
                type: 'POST',
                dataType: 'html',
                data: { page: 1, t: idata, category: cdata, chkPaging: false },
                cache: false,
                url: '/PromotionPage/BindProduct',
                success: function (data) {
                    $('#plcListPromotion').html(data);
                    var endPage = ReturnPagingAjax();
                    $('.productPromotionListItem .bb_paggingMore').remove();
                    $('.productPromotionListItem').append('<div class="bb_paggingMore"><a href="javascript:void(0)" rel="nofollow" cdata="' + cdata + '">Xem thêm (còn <span id="endRecord">' + endPage + '</span> sản phẩm)</a></div>');
                    if (endPage <= 0) {
                        $('.bb_paggingMore').remove();
                    }
                    $('.plcLoding').html('');
                    // load sort
                    loadSortClick();
                    lzLoading();
                    // paging more
                    PaggingMoreClick();
                },
                error: function () {
                    Console.log('Đã có lỗi xảy ra!');
                }
            });
        }, 500);

        removePage();
    });
}

function loadSortClick() {
    // active tab sort
    $('.totalP a').removeClass('p-ac-sort');
    var t = $('.totalPSort').attr('idata');
    if (t == 'mn' || t == 'bm' || t == 'pb') {
        $('.totalPSort a[idata$=' + t + ']').addClass('p-ac-sort');
    } else {
        $('.totalPSort a[idata$=mn]').addClass('p-ac-sort');
    }


    // click
    $('.totalP a').click(function () {
        var cmdPlc = $('#plcListPromotion');
        var idata = $(this).attr('idata');
        $('.plcLoding').append('<img src="/images/icons/gif-load-small.gif" width="30" height="30" class="promo-loading" />');
        // load product
        setTimeout(function () {
            $.ajax({
                type: 'POST',
                dataType: 'html',
                data: { page: 1, t: idata, chkPaging: false },
                cache: false,
                url: '/PromotionPage/BindProduct',
                success: function (data) {
                    $('#plcListPromotion').html(data);
                    var endPage = ReturnPagingAjax();
                    $('.productPromotionListItem .bb_paggingMore').remove();
                    $('.productPromotionListItem').append('<div class="bb_paggingMore"><a href="javascript:void(0)" rel="nofollow" cdata="">Xem thêm (còn <span id="endRecord">' + endPage + '</span> sản phẩm)</a></div>');
                    if (endPage <= 0) {
                        $('.bb_paggingMore').remove();
                    }
                    $('.plcLoding').html('');
                    // load sort
                    loadSortClick();
                    lzLoading();
                    // paging more
                    PaggingMoreClick();
                },
                error: function () {
                    Console.log('Đã có lỗi xảy ra!');
                }
            });
        }, 500);

        removePage();
        return false;
    });
}

function CategoryClick() {
    $('.spkmdm-listcate a').click(function () {
        var cmdPlc = $('#plcListPromotion');
        var cdata = $(this).attr('cdata');
        $('.plcLoding').append('<img src="/images/icons/gif-load-small.gif" width="30" height="30" class="promo-loading" />')
        // load product
        setTimeout(function () {
            $.ajax({
                type: 'POST',
                dataType: 'html',
                data: { page: 1, t: 'cat', category: cdata, chkPaging: false },
                cache: false,
                url: '/PromotionPage/BindProduct',
                success: function (data) {
                    $('#plcListPromotion').html(data);
                    var endPage = ReturnPagingAjax();
                    $('.productPromotionListItem .bb_paggingMore').remove();
                    $('.productPromotionListItem').append('<div class="bb_paggingMore"><a href="javascript:void(0)" rel="nofollow" cdata="' + cdata + '">Xem thêm (còn <span id="endRecord">' + endPage + '</span> sản phẩm)</a></div>');
                    if (endPage <= 0) {
                        $('.bb_paggingMore').remove();
                    }
                    $('.plcLoding').html('');
                    // load sort
                    loadSortClick();
                    lzLoading();
                    // paging more
                    PaggingMoreClick();
                },
                error: function () {
                    Console.log('Đã có lỗi xảy ra!');
                }
            });
        }, 500);

        // remove param url page
        removePage();
        return false;
    });
}

function PaggingMoreClick() {
    $('.bb_paggingMore a').click(function () {
        var page = $('input[name$=hidCurrentPage]').val();
        if (page != undefined) {
            page = parseInt(page) + 1;
        }
        var cmd = $(this);
        //alert(page);
        var total = cmd.children('#endRecord').text();
        var t = $('.totalPSort').attr('idata');
        var cdata = cmd.attr('cdata');
        $('.plcLodingMore').append('<img src="/images/icons/gif-load-small.gif" width="30" height="30" class="promo-loading" />');
        // load product

        $.ajax({
            type: 'POST',
            dataType: 'html',
            data: { page: page, t: t, category: cdata },
            cache: false,
            url: '/PromotionPage/BindProductPagging',
            success: function (data) {
                $('#plcListPromotion').append(data); // bind data moi
                var itemRecord = $('input[name$=hidItemRecord_' + page + ']').val();
                //set lai trang hien tai
                $('input[name$=hidCurrentPage]').val(page);
                // set lai tong so san pham con lai
                var totalend = parseInt(total) - parseInt(itemRecord);
                if (totalend <= 0) {
                    cmd.parent().remove();
                    $('.paggingCount').remove();
                } else {
                    cmd.children('#endRecord').text(totalend);
                }

                setTimeout(function () {
                    $('.plcLodingMore').html('');
                }, 500);
                // load sort
                loadSortClick();
                lzLoading();
            },
            error: function () {
                Console.log('Đã có lỗi xảy ra!');
            }
        });
    });
}

function backToTop() {
    $('body').append('<div id="top">Back to Top</div>');
    $(window).scroll(function () {
        if ($(window).scrollTop() != 0) {
            $('#top').fadeIn();
        } else {
            $('#top').fadeOut();
        }
    });
    $('#top').click(function () {
        $('html, body').animate({ scrollTop: 0 }, 500);
    });
}

function removeUrlFilter(url, paramNameRemove) {
    //tách url gốc thành 2 phần
    var partUrl = url.split('?');
    // tìm tham số cần sưa trên url thứ 2 partUrl[1]
    if (partUrl.length <= 1) {
        return partUrl[0];
    } else {
        //tách các tham số theo dấu &
        var params = partUrl[1].split('&');
        if (params.length <= 1) {
            //kiểm tra xem tham số này có phải tham số cần thay đổi không ?
            if (params[0].indexOf(paramNameRemove) >= 0) { //có chứa param cần tìm thì thay thế mới ngay
                return '';
            } else {
                return '?' + params[0];
            }
        } else {//nếu có nhiều tham số: duyệt từng thằng tìm và thay thế tham số
            var paramNew = '?';
            for (var i = 0; i < params.length; i++) {
                if (params[i].indexOf(paramNameRemove) < 0) {
                    paramNew += params[i] + '&';
                } else {
                    paramNew += '';
                }
            }
            return paramNew.substring(0, paramNew.length - 1);
        }
    }
}

function removePage() {
    var url = $(location).attr('href');
    var urlParam = url.split('?');
    var urlNew = removeUrlFilter(url, 'page');
    if (urlNew == '') {
        urlNew = urlParam[0];
    }
    window.history.replaceState(null, null, urlNew);
}

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
    return pattern.test(emailAddress);
};